#!/bin/bash

if [  "$1" != "start"  -a  "$1" != "stop"  -a  "$1" != "status" -a "$1" != "restart" ]; then
    echo "Usage: $0 {start|stop|status|restart}"
    exit 1
fi

if test -z $JAVA_HOME || [ ! -x $JAVA_HOME/bin/java ]; then
	echo "Need install jdk1.8!"
	exit 1
fi

APPLICATION_DIR=$(cd `dirname $0`; pwd)
cd $APPLICATION_DIR
APP_NAME=$(ls *.jar)
APP_PID_FILE=$APPLICATION_DIR/$APP_NAME.pid
APP_PID=-1

if [ -f $APP_PID_FILE ]; then
    APP_PID=$(cat $APP_PID_FILE) 
fi

tailLog(){
	while [ -f $APP_PID_FILE ]; do
	  APP_PID=$(cat $APP_PID_FILE)
      sleep 2
      if [ -x /proc/${APP_PID} ]; then
        echo "$APP_NAME(APP_PID=$APP_PID) is running"
      else
        echo 'bye --------------'
        break
      fi
	done
}


case "$1" in
  start)
  	if [ -x /proc/${APP_PID} ]; then
    	echo  "$APP_NAME(APP_PID=$APP_PID) is running"
    else
		echo "#############################################################################" >> start.log
		echo "#                      Starting $APP_NAME                       			  #" >> start.log
		echo "#############################################################################" >> start.log
    	cd $APPLICATION_DIR
		nohup $JAVA_HOME/bin/java -jar $APP_NAME --spring.config.location=application.properties  dir=$APPLICATION_DIR > start.log 2>&1 &
		RETVAL=$? 
		if [ $RETVAL -eq 0 ]; then  
      		echo "$APP_NAME(APP_PID=$!) start successed!"
      		echo "$(date +%G-%m-%e_%H-%M-%Ss):$APP_NAME(APP_PID=$!) start successed!" >> start.log
      		echo $! > $APP_PID_FILE
		tailLog
		else
    		echo "$APP_NAME start failed!"
		fi 
    fi
    ;;
  stop)
  	if [ -x /proc/${APP_PID} ]; then
  		echo "#############################################################################" >> start.log
		echo "#                      Stopping $APP_NAME                       			  #" >> start.log
		echo "#############################################################################" >> start.log
  		echo "kill -9 $APP_NAME(APP_PID=$APP_PID)"
    	kill -9 ${APP_PID}
    else
    	echo "$APP_NAME is not running"
    fi
    ;;
  status)
    if [ -x /proc/${APP_PID} ]; then
    	echo  "$APP_NAME(APP_PID=$APP_PID) is running"
    else
    	echo "$APP_NAME is not running"
    fi 
    ;;
 esac

exit 0

